
import 'dart:io';

import 'package:wakelock_plus/wakelock_plus.dart';
import 'package:share_fit/app/controllers/base/base_controller.dart';
import 'package:share_fit/app/helper/ext/tr_ext.dart';
import 'package:share_fit/app/helper/upgrade_helper.dart';
import 'package:share_fit/app/ute/uteped_const.dart';
import 'package:share_fit/app/ute/uteped_device.dart';
import 'package:share_fit/generated/locales.g.dart';

import 'upgrade_state.dart';

class UpgradeLogic extends BaseController {
  static const methodStartOTA = "startOTA";
  static const statusUnknown = 0;
  static const statusIDLE = 1;
  static const statusTransferring = 4;
  static const statusTransferred = 5;
  final UpgradeState state = UpgradeState();

  @override
  void onInit() {
    super.onInit();
    WakelockPlus.enable();
  }

  @override
  void onClose() {
    WakelockPlus.disable();
    super.onClose();
  }

  void doUpgrade() {
    var battery = UTEPedDevice.instance.battery;
    if (battery.isEmpty) {
      battery = "0";
    }

    if (int.parse(battery) < 40) {
      showTips(LocaleKeys.info.ts, LocaleKeys.battery_low_tips.ts);
      return;
    }
    state.upgradeStatus = statusTransferring;
    vRemoteReqAsync(methodStartOTA, {UTEPedConst.keyFile: state.upgradeFilePath});
    update();
  }

  bool isUpgrading() {
    return state.upgradeStatus == statusTransferring;
  }

  bool showUpgradeButton() {
    return state.upgradable && !isUpgrading();
  }

  @override
  String getRemotePath() {
    return "upgrade";
  }

  @override
  String getStoragePath() {
    return UTEPedConst.pathDevice;
  }

  @override
  void initState() {
    state.upgradeStatus = statusIDLE;
    _loadState();

    UpgradeHelper.instance.checkUpdate().then((value) => {
      _loadState(),
      update()
    });
  }

  void _loadState() {
    state.currentVersion = UTEPedDevice.instance.deviceInfo.versionName;
    state.upgradable = read(UTEPedConst.keyUpgradable, defaultValue: false);
    if (state.upgradable) {
      state.upgradeFilePath = read(UTEPedConst.keyUpgradeFilePath);
      var upgradeInfo = read(UTEPedConst.keyUpgradeInfo, defaultValue: {});
      if (upgradeInfo != null && upgradeInfo["version"] != null) {
        state.upgradeVersion = upgradeInfo["version"];
      }
    }

    if (!File(state.upgradeFilePath).existsSync()) {
      state.upgradable = false;
    }
  }

  @override
  void onRemoteEvent(event, method) {
    if (method == methodStartOTA) {
      var status = event[UTEPedConst.keyStatus];
      state.upgradeStatus = status;
      if (status == statusUnknown) {

      }
      else if (status == statusTransferring) {
        state.upgradePercent = double.parse(event[UTEPedConst.keyValue].toString())/100.0;
      }
      else if (status == statusTransferred) {
        state.upgradeStatus = statusIDLE;
        state.upgradable = false;
        state.currentVersion = state.upgradeVersion;
        remove(UTEPedConst.keyUpgradable);
      }
      update();
    }
  }
}
